package com.cnzhy.stream;

import com.alibaba.fastjson.JSON;
import com.cnzhy.stream.pojo.Dish;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhaoyan5
 */

@Slf4j
@SpringBootTest
public class StreamTest {

    public List<Dish> getDishList() {
        List<Dish> dishList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Dish dish = new Dish();
            dish.setCalories(1);
            dish.setName("Name_" + i);
            dishList.add(dish);
        }
        return dishList;
    }

    @Test
    public void beforeJava8() {
        List<Dish> lowCaloricDishes = new ArrayList<>();

        //1.筛选出卡路里小于400的菜肴
        for (Dish dish : getDishList()) {
            if (dish.getCalories() < 400) {
                lowCaloricDishes.add(dish);
            }
        }

        //2.对筛选出的菜肴进行排序
        Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
            @Override
            public int compare(Dish o1, Dish o2) {
                return Integer.compare(o1.getCalories(), o2.getCalories());
            }
        });

        //3.获取排序后菜肴的名字
        List<String> lowCaloricDishesNameList = new ArrayList<>();
        for (Dish d : lowCaloricDishes) {
            lowCaloricDishesNameList.add(d.getName());
        }
        log.info(JSON.toJSONString(lowCaloricDishesNameList));
    }

    @Test
    public void afterJava8() {
        List<String> lowCaloricDishesNameList = getDishList().stream().filter(d -> d.getCalories() < 400).sorted(Comparator.comparing(Dish::getName)).map(Dish::getName).collect(Collectors.toList());
        log.info(JSON.toJSONString(lowCaloricDishesNameList));
    }

}
